package com.assertionerror.loccounter.engine;

import com.assertionerror.loccounter.FileTypes;
import org.apache.log4j.Logger;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

/**
 * @author <a href="mailto:petrus@codewave.co.za">Petrus Pelser</a>
 */
public class FileRecursor implements FileReadable {

    private static final Logger LOG = Logger.getLogger(FileRecursor.class);
    private static final String TESTDIR = "c:\\projects\\loc_counter";

    private File path;
    private ArrayList<FileTypes> types;
    private ArrayList<FileReadListener> listeners = new ArrayList<FileReadListener>();

    public FileRecursor(File path, ArrayList<FileTypes> types) {
        this.path = path;
        this.types = types;
    }

    public Integer recurseDirectory() throws IOException {
        return recurseDirectory(path);
    }

    public Integer recurseDirectory(File dir) throws IOException {
        Integer count = 0;
        if (dir.isDirectory()) {
            File[] files = dir.listFiles();
            for (File file : files) {
                count += recurseDirectory(file);
            }
        } else {
            for (FileTypes type : types) {
                if (dir.getName().endsWith(type.ext)) {
                    count += new LineCounter().getLineCount(dir);

                    FileReadEvent event = new FileReadEvent(this);
                    event.setFileName(dir.getName());
                    fireReadListener(event);
                }
            }
        }

        return count;
    }

    public Integer getFileCount(File dir) throws IOException {
        Integer count = 0;

        if (dir.isDirectory()) {
            File[] files = dir.listFiles();
            for (File file : files) {
                count += getFileCount(file);
            }
        } else {
            for (FileTypes type : types) {
                if (dir.getName().endsWith(type.ext)) {
                    count++;
                }
            }
        }

        return count;
    }

    /*  Implemented methods */

    public void addFileReadListener(FileReadListener listener) {
        listeners.add(listener);
    }

    public void fireReadListener(FileReadEvent event) {
        for (FileReadListener listener : listeners) {
            listener.onRead(event);
        }
    }
}
